package org.tamal.servlet;

import java.io.IOException;
import java.util.Map;
import java.util.TimeZone;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.tamal.SessionKey;

/**
 * This is a general Utility Servlet.
 * @author Tamal Kanti Nath
 */
public class UtilityServlet extends HttpServlet {

	private static final long serialVersionUID = 154909309153013234L;

	@Override
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
    	setTimezone(request);
		addImage(request);
    }

	private static void addImage(HttpServletRequest request) {
		String name = request.getParameter("name");
		String data = request.getParameter("data");
		if (name == null || data == null) {
			return;
		}
		HttpSession session = request.getSession();
		@SuppressWarnings("unchecked")
		Map<String, String> images = (Map<String, String>) session
				.getAttribute(SessionKey.ATTACHMENTS.name());
		if (images == null) {
			images = new TreeMap<>();
			session.setAttribute(SessionKey.ATTACHMENTS.name(), images);
		}
		images.put(name, data);
	}

	private static void setTimezone(HttpServletRequest request) {
		String timezoneOffset = request.getParameter("timezoneOffset");
		String date = request.getParameter("date");
		if (date == null || timezoneOffset == null) {
			return;
		}
		int rawOffset = Integer.valueOf(timezoneOffset) * -60000;
		String[] timeZones = TimeZone.getAvailableIDs(rawOffset);
		for (String timeZone : timeZones) {
			TimeZone tz = TimeZone.getTimeZone(timeZone);
			if (date.contains(tz.getID()) || date.contains(tz.getDisplayName())) {
				request.getSession().setAttribute(SessionKey.TIMEZONE.name(),
						timeZone);
				break;
			}
		}
	}

}
